
$.fn.mapPicker = function (options) {
    
    var $this = $(this);

    if ($this.data('map-picker-loaded')) {
        return;
    } else {
        $this.data('map-picker-loaded', 1);
    }
    
    options = $.extend({
        lat: null,
        lng: null,
        callback: null,
    }, options);

    var id = 'weui-map-picker-' + $this.prop("id");

    var title, addr, lat, lng;

    var coord = '';

    if (parseFloat(options.lat) > 0 && parseFloat(options.lng) > 0) {
        coord = `&coord=${options.lat},${options.lng}`;
    }

    var $map = $(`

        <div id="${id}" class="weui-map-picker">
            <iframe class="weui-map-picker-container" src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&policy=1&key=Y2QBZ-DKV64-TWCUJ-XQFMU-YQWST-NJFLR&referer=wtsaas${coord}"></iframe>
            <div class="weui-map-picker-opr-area">
                <button type="button" class="weui-btn weui-btn_default">取消</button>
                <button type="button" class="weui-btn weui-btn_primary">确定</button>
            </div>
        </div>

    `);

    $("body").append($map);

    $(`#${id}.weui-map-picker .weui-map-picker-opr-area .weui-btn_default`).click(function () {
        $(".weui-map-picker").animate({top: '100%'}, 300);
    });

    $(`#${id}.weui-map-picker .weui-map-picker-opr-area .weui-btn_primary`).click(function () {
        if (!lat || !lng || !addr) {
            alert('请先选择地址');
            return false;
        }
        $(".weui-map-picker").animate({top: '100%'}, 300);
        options.callback && options.callback({title: title, addr: addr, lat: lat, lng: lng});
    });

    window.addEventListener('message', function (event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data;
        if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'

            title = loc.poiname;
            addr = loc.poiaddress;
            lat = loc.latlng.lat;
            lng = loc.latlng.lng;

        }
    }, false);

    $this.click(function () {

        $(`#${id}.weui-map-picker`).animate({top: '0%'}, 500);

    });

};